<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;
class BackupDatabase extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'db:backup';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    protected $process;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();


        /*$this->process = new Process([sprintf(
            'mysqldump -h%s -p%s -u%s -p%s %s > %s',
            env('DB_HOST'),
            env('DB_PORT'),
            env('DB_USERNAME'),
            env('DB_PASSWORD'),
            env('DB_DATABASE'),
            $filePath
        )]);*/
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        //Log::info('db:backup running');
        $dirPath = base_path('../../../../home/sqlBackup/');
        if (!file_exists($dirPath)) {
            mkdir($dirPath,0777,true);
        }

        //备份文件名以当前日期命名
        $filePath = $dirPath.date('Y-m-d').'.sql' ;
        system(sprintf(
            'mysqldump -h%s -p%s -u%s -p%s %s > %s',
            env('DB_HOST'),
            env('DB_PORT'),
            env('DB_USERNAME'),
            env('DB_PASSWORD'),
            env('DB_DATABASE'),
            $filePath
        ));
        //Log::info('db:backup end');
        return 0;
    }
}
